import { reqCartList,reqDeleteShopCart,reqChangeChecked} from "@/api"
import { Promise } from "core-js";

export default ({
    state:{
        cartList:[]
    },
    mutations:{
        GETCAETLIST(state,cartList){
            state.cartList=cartList;
        }
    },
    actions:{
        async getCartList({commit}){
            let result= await reqCartList()
            commit("GETCAETLIST",result.data);
        },
        async deleteShopCart({commit},skuId){
            let result= await reqDeleteShopCart(skuId);
            if(result.code==200){
                return "OK";
            }else{
                return Promise.reject(new Error('faile'))
            }
        },
        async changeChecked({commit},{skuId,isChecked}){
            let result=await reqChangeChecked(skuId,isChecked);
            if(result.code==200){
                return "OK";
            }else{
                return Promise.reject(new Error('faile'))
            }
        },
        // 删除勾选的产品
        deleteAllCheckedCart({getters,dispatch}){
            // context:小仓库，里面有 commit、getters 、dispatch
            // 获取购物车中的全部的产品（是一个数组）
            let PromiseAll=[];
            getters.cartList1.cartInfoList.forEach(item => {
                let promise=item.isChecked==1? dispatch('deleteShopCart',item.skuId):"";
                // 将每一次的返回的Promise添加到数组当中
                PromiseAll.push(promise);
            });
            // 该结果会在派发deleteAllCheckedCart事件的地方被接收到
            return Promise.all(PromiseAll) ;
        },
        changeAllChecked({dispatch,getters},isChecked){
            let PromiseAll=[]
            getters.cartList1.cartInfoList.forEach(item=>{
              let promise=  dispatch("changeChecked",{skuId:item.skuId,isChecked})
              PromiseAll.push(promise)
            })
            return Promise.all(PromiseAll)
        }
    },
    getters:{
        cartList1(state){
            return state.cartList[0] ||{};
        }
    }
})